import {
    reqLogin
} from "../../http/api"
import {
    Toast
} from "antd-mobile"
//初始值
const initState = {
    // 1.初始化user 
    user: {
        phone: "",
        password: ""
    },
    // 5.2.1 用户信息
    info: sessionStorage.getItem("info")?JSON.parse(sessionStorage.getItem("info")):{}

}

//action types
const types = {
    // 2.修改user 
    LOGIN_CHANGE_USER: "LOGIN_CHANGE_USER",
    // 5.2.2修改info 用户信息
    LOGIN_CHANGE_INFO: "LOGIN_CHANGE_INFO"
}


//action creator
export const actions = {
    // 4.修改user 
    changeUser: (key, value) => ({
        type: types.LOGIN_CHANGE_USER,
        key,
        value
    }),
    //5.登录逻辑
    loginAction: (push) => (dispatch, getState) => {
        let {
            user
        } = getState().login
        //登录请求
        reqLogin(user).then(res => {
            if (res.data.code === 200) {
                //5.1.弹成功
                Toast.info(res.data.msg, 1)
                // 5.2.存用户信息--初始值 info;修改info;导出info
                dispatch(actions.changeInfo(res.data.list))

                // 5.3.跳转页面
                push("/index/home")
            }
        })
    },
    // 5.2.4 修改info action 
    changeInfo: info => {
        if (info.token) {
            sessionStorage.setItem("info", JSON.stringify(info))
        } else {
            sessionStorage.removeItem("info")
        }
        return {
            type: types.LOGIN_CHANGE_INFO,
            info
        }
    }
}


//reducer
export const loginReducer = (state = initState, action) => {

    switch (action.type) {
        // 3.修改user 
        case types.LOGIN_CHANGE_USER:
            // {type:types.LOGIN_CHANGE_USER,key:"phone",value:"110"}
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
            break;
            // 5.2.3 修改info
        case types.LOGIN_CHANGE_INFO:
            return {
                ...state,
                info: action.info
            }
            break;
        default:
            return state;
    }
}

//导出数据
// 5.导出user 
export const getUser = state => state.login.user;
// 5.2.5.导出info
export const getInfo = state => state.login.info;
